var router = require('libs/router').router;
var pages = require('libs/pages');
var ItemMixin = require('mixins/item');
var libs = require('libs/libs');
var api = libs.api;
var _ = libs.lodash;
var store = require('mixins/store')
var pageData = false;

var Service = require('../_comm/service')
// var List = require('modules/list/load_list')(true, 'wsSendtime');
var _will_sent = {
    brand: 'xxx',
    count: 0
}

var _page = {
    onlineInfo: false
}

var _tmp_item = []

var _getLogin = SA.get('USER');       //获取login值

var bindEvent = function(){
    //预约时间所需要的js
    var getMobijs = SA.get('Mobiscrolljs')
    if (getMobijs && getMobijs ==='finish'){
        mobiscrolljs()
    }
    else{
        SA.set('Mobiscrolljs', mobiscrolljs)
    }
    function mobiscrolljs(){
        $('#demo_treelist1').mobiscroll().treelist({
            placeholder: '请选择服务时间',    //input的默认值
            display: 'bottom',               //弹窗的方式
            labels: ['服务器日期','服务器时间'],  // More info about labels: http://docs.mobiscroll.com/2-17-0/list#!opt-labels
            setText: '确定',
            cancelText: '取消'
        });
    }

    if (_page.onlineInfo){
        $('.dCy_branches').css('display','-webkit-box')
    }
    else {
        $('.dCy_branches').css('display','none')
    }

    //end
    var _waterNum = {};
    //水卡列表数量
    $('.waterList li').each(function(){
        var nowValue = $(this).find('.bl_no_num span');
        var userNum = $(this).find('.bL_com .bl_com_use');
        var _id = $(this).find('.bL_com em').attr('data-id')
        var _this_waterlist = $(this)
        _waterNum[_id] = {
            userN: parseInt(userNum.text())
            // userN: parseInt(userNum.text()) +1
        }
        if(parseInt(nowValue.html())<= 0){
            $(this).find('.bl_no_num').addClass('u-none');
        }else{
            $(this).find('.bl_no_num').removeClass('u-none');
        }
        $(this).find('.bL_num_add').on('touchstart',function(){
            num_add($(this), nowValue, userNum, _id);
        })
        // $(this).find('.bL_num_minus').on('touchstart',function(){
        // num_minus($(this), nowValue, userNum, _id);
        $(this).find('.bl_no_num').on('touchstart',function(){
            var no_num = $(this).find('.bL_num_minus')[0]
            num_minus($(no_num), nowValue, userNum, _id);
        })
    })

    function check_item(the, value, usernum, id){
        var _kkk;
        if (_tmp_item.length){
            _kkk = _tmp_item.pop()
            if (_kkk.id===id){
                _tmp_item.push(_kkk)
                return
            }
            _kkk.item.prev('.bl_no_num').addClass('u-none');
            _kkk.usernum.html(_kkk._val.usernum)
            _kkk.value.html(_kkk._val.value)
            _tmp_item.push({item: the, value: value, usernum: usernum, id: id, _val:{value: value.html(),usernum: usernum.html()}})
        }
        else {
            _tmp_item.push({item: the, value: value, usernum: usernum, id: id, _val:{value: value.html(),usernum: usernum.html()}})
        }
    }

    // 数量+事件
    function num_add(_this, value, usernum, id){
        check_item(_this, value, usernum, id)
        if (_waterNum[id]){
            _this.prev('.bl_no_num').removeClass('u-none');
            if(parseInt(value.html()) < _waterNum[id].userN){
                usernum.html(parseInt(usernum.html()) - 1);
                value.html(parseInt(value.html()) +1);
            }
        }
    }
    // 数量-事件
    function num_minus(_this, value, usernum, id){
        if(_waterNum[id]){
            usernum.html(parseInt(usernum.html()) + 1);
            value.html(parseInt(value.html()) - 1)
            if(parseInt(value.html()) <= 0){
                value.html() == 0;
                usernum.html() == _waterNum[id].nserN;
                _this.parent('.bl_no_num').addClass('u-none')
            }
        }
    }

    //点击默认地址切换到用户中心的地址
    $('#waterSend_address').click(function(){
        SA.set('_GoBack', 'water/send')
        router('uc/addresslist')
    })

    //点击提交订单的api
    $('#waterSendBtn').click(function(){
        var wcSum = 0;
        var waterSendListgroup = [];
        var _address = $('.waterSend_address_address').attr('data-id');
        $('.waterList li').map(function(){
            wcSum += parseInt($(this).find('.bl_no_num span').html());
            console.log($(this).find('.bl_no_num span').html());
            if($(this).find('.bl_no_num span').html()>0){
                waterSendListgroup.push(
                    $(this).find('.bL_com em').attr('data-id')+ '_' +$(this).find('.bl_no_num span').html()
                )
            }
        })
        if(!_address){
            ui.alertBox({
                cons: [{text: '配送地址不能为空', name: "smallCon"}],
                btns: [
                    {
                    text: '确认',
                    close: true
                }]
            })
        }
        else if(wcSum == 0){
            ui.alertBox({
                cons: [{text:'请至少选择一桶水',name:"bigCon"}],
                btns: [
                ]
            })
        }else{
            if($('#demo_treelist1_dummy').val()){

                ui.alertBox({
                    cons: [{text: '确认提交订单', name: "smallCon"}],
                    btns: [
                        {
                            text: '取消',
                            close: true
                        },
                        {
                            text: '确认',
                            close: true,
                            callback: function(){
                                _submit()
                            }
                        }
                    ]
                })

                function _submit(){
                    var waterSend_post = {
                        login: SA.get('USER').login,
                        userCardIds: waterSendListgroup.join(','),
                        userName: $('#waterSend_address .waterSend_address_name').html(),
                        userPhone: $('#waterSend_address .waterSend_address_phone').html(),
                        address: $('#waterSend_address .waterSend_address_address').html(),
                        time: $('#demo_treelist1_dummy').val(),
                        addressId: _address,
                        // time: '2016-03-09 08:00~18:00',
                        remark: $('#waterSendNote').val(),
                        bookDate: $("#demo_treelist1_dummy").val().substring(0,10),
                        bookTime: _.trim($("#demo_treelist1_dummy").val().substring(11)),
                        method: 'get'
                    }
                    api.req('/watersendOrder', waterSend_post, function(data){
                        console.log(data);
                        if(data){
                            if (data.code||data.code==0){
                                ui.alertBox({
                                    cons: [{text:data.message,name:"littleCon"}],
                                    btns: [
                                    ]
                                })
                            }
                            else {
                                ui.alertBox({
                                    cons: [{text:'下单已成功',name:"bigCon"}, {text: '等待管家上门送水', name: "smallCon"}],
                                    btns: [
                                        {
                                            text: '查看订单详情',
                                            close: true,
                                            callback: function () {
                                                router('water/item',{back: data.orderId})
                                            }
                                        }
                                    ],
                                    cols:function (){
                                        delete_zeroData()
                                    }
                                })

                            }
                        }else{
                            ui.alertBox({
                                cons: [{text:'提交订单失败！',name:"bigCon"}],
                                btns: [
                                ]
                            })
                        }
                    })
                }
            }else{
                ui.alertBox({
                    cons: [{text:'请选择预约时间',name:"bigCon"}],
                    btns: [
                    ]
                })
            }

        }
    });
    function delete_zeroData(){
        $('.waterList li').each(function(){
            var userNum = $(this).find('.bL_com .bl_com_use').text();
            if(userNum === 0){
                $(this).remove()
            }
        })
    };
    $('#waterCardlink a').click(function(){
        router('water/card')
        // var orderIds = '77aa895f92c24ca480f385a9def7c1d7'
        // router('water/item',{back: orderIds})
        // return false;
    });
    $('.express').click(function(){
        router('express');
    });
    $('.send').click(function(){
        router('send/send');
    });
    // $('.water').click(function(){
    //     router('water/send');
    // });
    $('.waterCard').click(function(){
        router('water/card');
    });
    $('.dCy_branches').click(function(){
        router('uc/siteIntroduce');
    });
    //短信订阅
    $('.subscribe_btn_water').click(function(){
        router('uc/sms',{'back':'water/send'});
    });
    //点击网点介绍
    $('.default_label_branches').click(function(){
        router('uc/siteIntroduce');
    });
    $('.userCenter').click(function(){
        SA.set('_GoBack', 'water/send')
        router('uc/index',{'back':'water/send'});
    })
    setTimeout(function(){
        $('#water_send').find('.flex-1').animate({scrollTop: '1000px'}, 1000)
    },500)

    // 点击备注时，滚动到底
    $('#waterSendNote').click(function(){
        setTimeout(function(){
            $('#water_send').find('.flex-1')[0].scrollTop=1000;
        },300)
    })

    if($('.water_no_card_com').length){
        $('.default_foot').css('display','none')
    }else{
        $('.default_foot').css('display','block')
    }

    $('.defult_addrss_selected p').each(function(){
        if($(this).find('span').html() == '请输入收件人姓名' ||
            $(this).find('span').html() == '请输入收件人电话' ||
            $(this).find('span').html() == '请选择小区'
        ){
            $(this).find('span').css('color','#c5c5c5')
        }
    })
}
//时间插件所需要的html结构 start
function Waytime(data){
    var abc = []
    if (!data.length){
        return abc;
    }
    data.map(function(item, i){
        abc.push(
            <li data-val={item} key={'waytime'+i}>
                {item}
            </li>
        )
    })
    return <ul>{abc}</ul>
}
//end
//获取水卡列表数据并生成结构
var WaterListdata = React.createClass({
    render: function(){
        var WaterList_data = this.props.data;
        // var waterRemain = WaterList_data.remainNum -1;      //默认值为1时
        return(
            <li>
                <div className="bL_pic"><img src={WaterList_data.url} /></div>
                <div className="bL_com">
                    <em  data-id={WaterList_data.userCardId}>{WaterList_data.cardName}</em>
                    <span className="bL_com_pp">
                        <i>品牌：{WaterList_data.skuName}</i>
                        <i>规格：{WaterList_data.unit}</i>
                    </span>
                    <p><span>剩余：</span><i><span className="bl_com_use">{WaterList_data.remainNum}</span>/<span className="bl_com_use_all">{WaterList_data.totalNum}</span></i></p>
                </div>
                <div className="bL_num">
                    <div className="bl_no_num">
                        <i className="iconfont icon-jikediancanicon08 bL_num_minus"></i>
                        <span>0</span>
                    </div>
                    <i className="iconfont icon-jia1 bL_num_add"></i>
                </div>
            </li>
        )
    }
})


//end
var WaterSend = React.createClass({
    mixins: [ItemMixin],
    componentWillMount:function(){
        if (this.props.data){
            this.setState({
                waterHtmlData_all: this.props.data
            })
        }
        if (this.props.info){
            this.setState({
                waterInfo: this.props.info
            })
        }
    },

    willMount: function(){
        var waterHtmlData_all = this.state.waterHtmlData_all  || {};
        var waterHtmladdress_data = waterHtmlData_all.address || []
        var watersendTime = [];
        var watersendList = [];
        if(waterHtmlData_all.waterCards && waterHtmlData_all.waterCards.length){
            waterHtmlData_all.appointTimes.map(function(item, i){
                if (item.times.length){
                    var times = Waytime(item.times)
                    watersendTime.push(
                        <li data-val={item.date} key={'appointTimes'+i}>
                            {item.date}
                            {times}
                        </li>
                    )
                }
            })
            waterHtmlData_all.waterCards.map(function(item, i){
                watersendList.push(
                    <WaterListdata data={item}/>
                )
            })
            return(
                <div className="water_card mT01 pB055">
                    <ul className="buyList waterList box-shadow">
                        {watersendList}
                    </ul>
                    <div className="default_pd016 mT01 box-shadow" id='waterSend_address'>
                        <div className="defult_addrss_selected">
                            <p><label>姓名</label><span className='waterSend_address_name'>{waterHtmladdress_data.contact?waterHtmladdress_data.contact:'请输入收件人姓名'}</span></p>
                            <p><label>电话</label><span className='waterSend_address_phone'>{waterHtmladdress_data.contactPhone?waterHtmladdress_data.contactPhone:'请输入收件人电话'}</span></p>
                            <p><label>地址</label><span data-id={waterHtmladdress_data.id} className='waterSend_address_address'>{waterHtmladdress_data.fullAddress?waterHtmladdress_data.fullAddress:'请选择小区'}</span></p>
                            <i className="iconfont icon-xiangyou"></i>
                        </div>
                    </div>
                    <div data-role="fieldcontain" className="default_pd016 box-shadow u-mt-15 m-form" id="demo_cont_treelist">
                        <label>预约时间</label>
                        <ul id="demo_treelist1" className="u-none">
                            {watersendTime}
                        </ul>
                    </div>
                    <div className="default_pd016 mT01 default_note box-shadow">
                        <div className="d_note_head u-border-none">
                            <label>备注</label>
                            <textarea placeholder="添加备注信息" id='waterSendNote'></textarea>
                        </div>
                    </div>
                </div>
            )
        }
        else{
            return(
                <div className="water_no_card mT01">
                    <div className="water_no_card_com box-shadow">
                        <i></i><p>您还没有水卡 请先购买水卡</p>
                    </div>
                    <div className="f_submit" style={{padding:'0.2rem 0'}} id="waterCardlink"><a href="javascript:;" className="f_btn">购买水卡</a></div>
                </div>
            )
        }

    },
    render: function(){
        // var dCydata = this.showonlineWillMount()
        var watersend_cardlist = this.willMount();

        var onlineStatus;
        if(this.state.waterHtmlData_all.user.isReceiveSms == true){
            onlineStatus = '短信已订阅'
        }else{
            onlineStatus = '短信订阅'
        }
        return(
            <div className="expressWarp flex flex-v">
                <div className="flex-1 f-oTouch">
                    <div className="nav box-shadow">
                        <div className="express">
                            <a href="javascript:;">
                                <div className="nav-icon">
                                    <img src="/images/express.png" alt="" />
                                </div>
                                <div className="nav-text"><span>我要收件</span></div>
                            </a>
                        </div>
                        <div className="send">
                            <a href="javascript:;">
                                <div className="nav-icon">
                                    <img src="/images/send.png" alt="" />
                                </div>
                                <div className="nav-text"><span>快递寄件</span></div>
                            </a>
                        </div>
                        <div className="water">
                            <a href="javascript:;" className="active">
                                <div className="nav-icon">
                                    <img src="/images/water.png" alt="" />
                                </div>
                                <div className="nav-text"><span>预约送水</span></div>
                            </a>
                        </div>
                        <div className="waterCard">
                            <a href="javascript:;">
                                <div className="nav-icon">
                                    <img src="/images/waterCard.png" alt="" />
                                </div>
                                <div className="nav-text"><span>购买水卡</span></div>
                            </a>
                        </div>
                    </div>
                    <div className="u-mt-15 box-shadow app_index userCenter">
                        <ul className="default_Picture">
                            <li className="uc_coupon">
                                <div>
                                    <img src="/images/icon-user_03.png" alt=""  className="userImg"/>
                                </div>
                                <label className="userTit">个人中心</label>
                                <i className="iconfont icon-xiangyou"></i>
                            </li>
                        </ul>
                    </div>
                    <div className="mT01 default_pd016 default_community box-shadow">
                        <h3>社区便民</h3>
                        <ul>
                            <Service data={this.state.waterInfo}/>

                            <li className="dCy_notice">
                                <div className="dCy_pic">
                                    <img src="/images/img_tu2.png" alt="" />
                                </div>
                                <div className="dCy_b_com">
                                    <div className="dCy_n_com">
                                        <em>小区公告</em>
                                        <p>左邻右里最新动态信息</p>
                                    </div>
                                    <div className="f_submit">
                                        <a className="f_btn subscribe_btn subscribe_btn_water"><i className="iconfont icon-975shoujitongxinlu"></i>{onlineStatus}</a>
                                    </div>
                                </div>
                            </li>
                        </ul>
                    </div>
                    {watersend_cardlist}
                    <div className="default_foot default_foot_btn3 defalut_color">
                        <a href='javascript:;' id="waterSendBtn">提交订单</a>
                    </div>
                </div>
            </div>
        )
    }
})

function wsAdressBack(){
    _this = this;
    var waterHtmlData_post = {
        login: SA.get('USER').login,
        // bizId: '1',
        // bizId: 'a64e35d02f224021806cf42830d83758',       //测试环境里的业务id
        method: 'get'
    }

    api.req('/onlineInfo',{login: SA.get('USER').login, method:'get'}, function(info){
        if(!info.code){
            _page.onlineInfo = true;
            SA.setter('ONLINE1', {data: info})

            api.req('/waterHtmlData', waterHtmlData_post, function(data){
                console.log(data);
                if(data.code == '114000' || data.code == '115000'){
                    router('uc/location')
                }else{
                    pageData = data;
                    _this.main(_this, data, info);
                }
            })
        }
    })



}

function start(name){
    return pages.new({
        boot: function(){
        },
        trigger: function(self, data){
            this.libs.changeTitle('服务');
            wsAdressBack.call(this)
        },
        goback: function(){
            router.cb = function(){
                if (wx){
                    wx.closeWindow()
                }
            }
            // var _pre = router.pre();
            // if (_pre.hash==='login'){
            //     router.cb=function(){
            //         if (wx){
            //             wx.closeWindow()
            //         }
            //     }
            // }
            // else {
            //     router.cb=function(){
            //         router.goback()
            //     }
            // }
        },
        main: function(self, data, info){
            this.render(
                <WaterSend itemDefaultMethod={bindEvent} data={data} info={info} />,
                document.getElementById(name)
            )
        },
        end: function(){
            SA.deleter('ONLINE1')
            _will_sent = {
                brand: 'xxx',
                count: 0
            }
            React.unmountComponentAtNode(document.getElementById(name))
        }
    })
}


module.exports = start;
